package com.tinyengine.it.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tinyengine.it.model.dto.TransResultDTO;
import com.tinyengine.it.model.dto.TranslateDTO;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Random;
public class TranslateUtils {

    private static final String URL = "https://fanyi-api.baidu.com/api/trans/vip/translate?";
    private static final String APP_ID = "20221201001479559";
    private static final String SECRET_KEY = "PB81N8QgnoTq6laaPzXm";

    public static TransResultDTO translate(String sourceText) throws Exception {
        String q = sourceText;
        String from = "zh";
        String to = "en";
        Random rd = new Random();
        String salt = String.valueOf(rd.nextInt(100000));
        String sign = encryptString(APP_ID + q + salt + SECRET_KEY);

        String requestUrl = URL + "q=" + URLEncoder.encode(q, "UTF-8") +
                "&from=" + from + "&to=" + to +
                "&appid=" + APP_ID + "&salt=" + salt + "&sign=" + sign;

        HttpURLConnection connection = (HttpURLConnection) new URL(requestUrl).openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
        connection.setConnectTimeout(6000);

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        ObjectMapper objectMapper = new ObjectMapper();
        TranslateDTO translateDTO = objectMapper.readValue(response.toString(), TranslateDTO.class);
        return translateDTO.getTrans_result().get(0);
    }

    public static void main(String[] args) throws Exception {
        new TranslateUtils().translate("你好");

    }

    private static String encryptString(String str) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] byteOld = str.getBytes("UTF-8");
        byte[] byteNew = md.digest(byteOld);
        StringBuilder sb = new StringBuilder();
        for (byte b : byteNew) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}
